package com.alex.service.Search_Plans;

import co.elastic.clients.elasticsearch._types.query_dsl.MultiMatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;

import java.util.Set;

import static com.alex.service.Search_Plans.SearchPlanUtils.enWordIgnore;
import static com.alex.utils.MyUtils.zsout;


/**
 * @Author: 张福垒
 * @Date: 2024/11/27 16:32
 * @Description: [全部] 分词检索
 * @phone: 13864677931
 */
public class One_Field_Match_query {
    /**
     * 针对主题的 分词的检索方法 根据输入的单次或者汉字长度来判断需要命中X/Y 或者 X% 之多少的数字
     *
     * @param value
     * @return
     */
    public static Query one_field_match_query(String field, String value, boolean printLog) {
        int wordCount = value.length();  //默认算中文检索词的字数
        String minimumMatch;
        //首先判断中英文混合输入的情况
        if (SearchPlanUtils.isContainChineseAndEnglish(value)) {
            zsout("[OneField][混合][CN][EN][" + wordCount + "]   " + value, printLog);
            if (wordCount <= 10) {
                minimumMatch = "99%";
            } else {
                minimumMatch = "95%";
            }
            String finalFreeWord1 = value;
            return MultiMatchQuery.of(i -> i.fields(
                    field
            ).query(finalFreeWord1).minimumShouldMatch(minimumMatch))._toQuery();
        }
        /**
         * 只有中文或者只有英文的时候
         */
        Set<String> set = enWordIgnore();
        for (String oneWord : set) {
            if (value.contains(" " + oneWord + " ")) {
                value = value.replaceAll(" " + oneWord + " ", " ");
                value = value.replaceAll(" +", " ").trim();
            }
        }
        if (!SearchPlanUtils.isContainChinese(value)) {//不过不包含中文就算单词个数
            wordCount = value.split("\\s+").length;
            zsout("[OneField][分词][EN][" + wordCount + "]   " + value, printLog);
        } else {
            zsout("[OneField][分词][CN][" + wordCount + "]   " + value, printLog);
        }
        switch (wordCount) {
            case 1:
                minimumMatch = "100%";
                break;
            case 2:
                minimumMatch = "100%";
                break;
            case 3:
                minimumMatch = "100%";
                break;
            case 4:
                minimumMatch = "100%";
                break;
            default:
                minimumMatch = "99%";
                break;
        }


        String finalFreeWord = value;
        return MultiMatchQuery.of(i -> i.fields(
                field
        ).query(finalFreeWord).minimumShouldMatch(minimumMatch))._toQuery();
    }


}
